package org.jeecg.modules.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.entity.MesEmployeeWorkType;
import org.jeecg.modules.mes.entity.MesWorkType;
import org.jeecg.modules.mes.mapper.MesWorkTypeMapper;
import org.jeecg.modules.mes.service.IMesEmployeeWorkTypeService;
import org.jeecg.modules.mes.service.IMesWorkTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 工种类型定义表 Service 实现类
 */
@Slf4j
@Service
public class MesWorkTypeServiceImpl extends ServiceImpl<MesWorkTypeMapper, MesWorkType> implements IMesWorkTypeService {

    @Autowired
    private MesWorkTypeMapper workTypeMapper;

    @Autowired
    private IMesEmployeeWorkTypeService employeeWorkTypeService;

    @Override
    public IPage<MesWorkType> queryPageList(Page<MesWorkType> page, Map<String, Object> params) {
        return workTypeMapper.queryPageList(page, params);
    }

    @Override
    public List<MesWorkType> getAllWorkTypes() {
        QueryWrapper<MesWorkType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 启用状态
        queryWrapper.orderByAsc("sort_order", "work_type_code");
        
        return this.list(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<MesWorkType> saveWorkType(MesWorkType workType) {
        try {
            // 检查工种编码是否已存在
            if (checkWorkTypeCodeExists(workType.getWorkTypeCode(), null)) {
                return Result.error("工种编码已存在，请使用其他编码");
            }

            workType.setCreateTime(new Date());
            
            // 设置默认值
            if (workType.getStatus() == null) {
                workType.setStatus(1);
            }
            if (workType.getSortOrder() == null) {
                workType.setSortOrder(0);
            }
            
            this.save(workType);
            
            return Result.OK("工种类型添加成功", workType);
        } catch (Exception e) {
            log.error("保存工种类型失败", e);
            return Result.error("保存工种类型失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<MesWorkType> updateWorkType(MesWorkType workType) {
        try {
            // 检查工种编码是否已存在（排除当前记录）
            if (checkWorkTypeCodeExists(workType.getWorkTypeCode(), workType.getId())) {
                return Result.error("工种编码已存在，请使用其他编码");
            }
            
            // 获取当前用户信息
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            workType.setUpdateBy(sysUser.getUsername());
            workType.setUpdateTime(new Date());
            
            this.updateById(workType);
            
            return Result.OK("工种类型更新成功", workType);
        } catch (Exception e) {
            log.error("更新工种类型失败", e);
            return Result.error("更新工种类型失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> removeWorkType(String id) {
        try {
            MesWorkType workType = this.getById(id);
            if (workType == null) {
                return Result.error("工种类型不存在");
            }
            
            // 删除相关的员工工种分配
            employeeWorkTypeService.removeByWorkTypeId(id);
            
            // 删除工种类型
            this.removeById(id);
            
            return Result.OK("工种类型删除成功");
        } catch (Exception e) {
            log.error("删除工种类型失败", e);
            return Result.error("删除工种类型失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> removeWorkTypes(List<String> ids) {
        try {
            for (String id : ids) {
                // 删除相关的员工工种分配
                employeeWorkTypeService.removeByWorkTypeId(id);
            }
            
            // 批量删除工种类型
            this.removeByIds(ids);
            
            return Result.OK("批量删除工种类型成功");
        } catch (Exception e) {
            log.error("批量删除工种类型失败", e);
            return Result.error("批量删除工种类型失败：" + e.getMessage());
        }
    }

    @Override
    public boolean checkWorkTypeCodeExists(String workTypeCode, String excludeId) {
        if (StringUtils.isBlank(workTypeCode)) {
            return false;
        }
        
        int count = workTypeMapper.checkWorkTypeCodeExists(workTypeCode, excludeId);
        return count > 0;
    }

    @Override
    public List<Map<String, Object>> getWorkTypeEmployees(String workTypeId) {
        if (StringUtils.isBlank(workTypeId)) {
            return null;
        }
        return workTypeMapper.getWorkTypeEmployees(workTypeId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> addEmployeesToWorkType(Map<String, Object> requestData) {
        try {
            String workTypeId = (String) requestData.get("workTypeId");
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> employees = (List<Map<String, Object>>) requestData.get("employees");
            
            if (StringUtils.isBlank(workTypeId) || employees == null || employees.isEmpty()) {
                return Result.error("参数不能为空");
            }

            // 获取当前用户信息
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            String currentUser = sysUser.getUsername();
            Date currentTime = new Date();

            // 批量添加员工到工种
            for (Map<String, Object> employeeData : employees) {
                String employeeId = (String) employeeData.get("employeeId");
                String employeeName = (String) employeeData.get("employeeName");
                Object skillLevelObj = employeeData.get("skillLevel");
                Integer skillLevel = skillLevelObj != null ? Integer.valueOf(skillLevelObj.toString()) : null;
                String certifier = (String) employeeData.get("certifier");
                Date certificationDate = null;
                Date expiryDate = null;
                
                // 处理日期字段 - 安全的日期转换
                Object certificationDateObj = employeeData.get("certificationDate");
                if (certificationDateObj != null) {
                    if (certificationDateObj instanceof Date) {
                        certificationDate = (Date) certificationDateObj;
                    } else if (certificationDateObj instanceof String) {
                        try {
                            certificationDate = new SimpleDateFormat("yyyy-MM-dd").parse(certificationDateObj.toString());
                        } catch (Exception e) {
                            log.warn("无法解析认证日期: {}", certificationDateObj);
                        }
                    }
                }
                
                Object expiryDateObj = employeeData.get("expiryDate");
                if (expiryDateObj != null) {
                    if (expiryDateObj instanceof Date) {
                        expiryDate = (Date) expiryDateObj;
                    } else if (expiryDateObj instanceof String) {
                        try {
                            expiryDate = new SimpleDateFormat("yyyy-MM-dd").parse(expiryDateObj.toString());
                        } catch (Exception e) {
                            log.warn("无法解析过期日期: {}", expiryDateObj);
                        }
                    }
                }

                // 检查是否已存在该员工工种分配
                if (!employeeWorkTypeService.checkEmployeeWorkTypeExists(employeeId, workTypeId, null)) {
                    // 获取工种信息
                    MesWorkType workType = this.getById(workTypeId);
                    if (workType != null) {
                        MesEmployeeWorkType employeeWorkType = new MesEmployeeWorkType();
                        employeeWorkType.setEmployeeId(employeeId);
                        employeeWorkType.setEmployeeName(employeeName);
                        employeeWorkType.setWorkTypeId(workTypeId);
                        employeeWorkType.setWorkTypeCode(workType.getWorkTypeCode());
                        employeeWorkType.setWorkTypeName(workType.getWorkTypeName());
                        employeeWorkType.setSkillLevel(skillLevel != null ? skillLevel : 1);
                        employeeWorkType.setStatus(1); // 默认启用
                        employeeWorkType.setCertificationDate(certificationDate);
                        employeeWorkType.setExpiryDate(expiryDate);
                        employeeWorkType.setCertifier(certifier);
                        employeeWorkType.setCreateBy(currentUser);
                        employeeWorkType.setCreateTime(currentTime);

                        employeeWorkTypeService.save(employeeWorkType);
                    }
                }
            }

            return Result.OK("员工添加成功");
        } catch (Exception e) {
            log.error("添加员工到工种失败", e);
            return Result.error("添加员工到工种失败：" + e.getMessage());
        }
    }
}
